//
//  IntegralViewController.m
//  YaoHeAPP
//
//  Created by 杨亚森 on 16/5/12.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "IntegralViewController.h"
#import "Masonry.h"
#import "SVPullToRefresh.h"
#import "Controller.h"
#import "UIMacros.h"
#import "IntegralModel.h"
#import "MJExtension.h"
#import "IntegralTableViewCell.h"

#define kNormalCellIdentifier @"normalCellIdentifier"

@interface IntegralViewController () <UITableViewDataSource, UITableViewDelegate> {
    int _pageNum;                                                           // 页数,传参使用
}

@property (nonatomic, strong) UILabel *totalIntegralLabel;                  // 积分总额label
@property (nonatomic, strong) UITableView *integralTableView;               // tableView
@property (nonatomic, strong) NSMutableArray *dataSource;                   // tableView数据源

@end

@implementation IntegralViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"IntegralViewController"];
    
    [[self rdv_tabBarController] setTabBarHidden:YES animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"IntegralViewController"];
    
    [[self rdv_tabBarController] setTabBarHidden:NO animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = bgVCcolor;
    //加一个导航条
    UIView *navcBar = [[UIView alloc] init];
    navcBar.backgroundColor = [UIColor colorWithRed:90.f/255.f green:191.f/255.f blue:219.f/255.f alpha:1];
    [self.view addSubview:navcBar];
    [self.view bringSubviewToFront:navcBar];
    [navcBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);   make.left.offset(0);
        make.height.offset(60);  make.right.offset(0);
    }];
    
    //导航条标题
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"我的积分";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [UIColor whiteColor];
    [navcBar addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(25);
        make.left.offset(self.view.frame.size.width/2-70);
        make.width.offset(140);
        make.height.offset(30);
    }];
    
    //返回按钮
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"return"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backLogin) forControlEvents:UIControlEventTouchUpInside];
    [navcBar addSubview:leftButton];
    [leftButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(6);
        make.width.offset(30);
        make.height.offset(28);
        make.top.offset(25);
    }];
    
    // 积分总额背景View
    UIView *totalIntegralView = [[UIView alloc] initWithFrame:CGRectMake(0, 70, self.view.width, 60)];
    totalIntegralView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:totalIntegralView];
    
    // @"积分总额"label
    UILabel *jifenzongeLabel = [[UILabel alloc] initWithFrame:CGRectMake((self.view.width-60)/2, 5, 60, 20)];
    jifenzongeLabel.font = Font(12);
    jifenzongeLabel.textAlignment = NSTextAlignmentCenter;
    jifenzongeLabel.text = @"积分总额";
    [totalIntegralView addSubview:jifenzongeLabel];
    
    // 积分label
    UILabel *totalIntegralLabel = [[UILabel alloc] initWithFrame:CGRectMake((self.view.width-120)/2, jifenzongeLabel.bottom+10, 120, 20)];
    totalIntegralLabel.textColor = [UIColor redColor];
    totalIntegralLabel.font = Font(15);
    totalIntegralLabel.textAlignment = NSTextAlignmentCenter;
    [totalIntegralView addSubview:totalIntegralLabel];
    self.totalIntegralLabel = totalIntegralLabel;
    
    // 近一个月积分记录View
    UIView *integralRecordView = [[UIView alloc] initWithFrame:CGRectMake(0, totalIntegralView.bottom+10, self.view.width, 40)];
    integralRecordView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:integralRecordView];
    
    // 近一个月积分记录Label
    UILabel *integralRecordLabel = [[UILabel alloc] initWithFrame:CGRectMake((self.view.width-120)/2, 10, 120, 20)];
    integralRecordLabel.font = Font(13);
    integralRecordLabel.textAlignment = NSTextAlignmentCenter;
    integralRecordLabel.textColor = [UIColor redColor];
    integralRecordLabel.text = @"近一个月积分记录";
    [integralRecordView addSubview:integralRecordLabel];
    
    // 下划线View
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, integralRecordView.height-1, self.view.width, 1)];
    lineView.backgroundColor = [UIColor lightGrayColor];
    [integralRecordView addSubview:lineView];
    
    // 积分tableView
    UITableView *integralTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, integralRecordView.bottom, self.view.width, self.view.height-integralRecordView.bottom) style:UITableViewStylePlain];
    integralTableView.delegate = self;
    integralTableView.dataSource = self;
    [self.view addSubview:integralTableView];
    self.integralTableView = integralTableView;
    
    //放置下拉上拉刷新控件
    __weak IntegralViewController *weakSelf = self;
    
    [self.integralTableView addPullToRefreshWithActionHandler:^{
        [weakSelf loadNewData];
    }];
    
    [self.integralTableView addInfiniteScrollingWithActionHandler:^{
        [weakSelf loadMoreData];
    }];
    
    // loadData请求数据
    [self loadNewData];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    IntegralTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kNormalCellIdentifier];
    if (!cell) {
        cell = [[IntegralTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kNormalCellIdentifier];
    }
    IntegralModel *integralModel = self.dataSource[indexPath.row];
    cell.integralModel = integralModel;
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 45;
}


#pragma mark - other method
- (void)loadNewData {
    __weak IntegralViewController *weakSelf = self;
    
    _pageNum = 0;           // 刷新时页数置为0
    
    [weakSelf.integralTableView beginUpdates];
    
    NSMutableDictionary *paramDict = [[NSMutableDictionary alloc] init];
    [paramDict setObject:[NSNumber numberWithInt:_pageNum] forKey:@"page_num"];
    [paramDict setObject:pageStep forKey:@"page_step"];
    
    [Controller requestWithURL:IntegralRecords jsondic:paramDict finishBlock:^(ClassData* data) {
        if ([data.number isEqualToNumber:@0]) {
            NSDictionary *dic = [NSDictionary dictionaryWithDictionary:data.data];
            
            if (weakSelf.dataSource.count > 0) {
                [weakSelf.dataSource removeAllObjects];
            }
            
            for (NSArray* array in dic[@"DATA"]) {
                IntegralModel *integralModel = [IntegralModel mj_objectWithKeyValues:array];
                [weakSelf.dataSource addObject:integralModel];
            }
            [weakSelf.integralTableView reloadData];
            weakSelf.totalIntegralLabel.text = [NSString stringWithFormat:@"%@", dic[@"TOTAL_SCORE"]];
        } else {
            NSLog(@"请求失败");
        }
    }];
    // 3. 结束刷新(相当于动画)
    [weakSelf.integralTableView endUpdates];
    [weakSelf.integralTableView.pullToRefreshView stopAnimating];
    
}

- (void)loadMoreData {
    __weak IntegralViewController *weakSelf = self;
    
    _pageNum++;           // 加载更多时页数++
    
    [weakSelf.integralTableView beginUpdates];
    
    NSMutableDictionary *paramDict = [[NSMutableDictionary alloc] init];
    [paramDict setObject:[NSNumber numberWithInt:_pageNum] forKey:@"page_num"];
    [paramDict setObject:pageStep forKey:@"page_step"];
    
    [Controller requestWithURL:IntegralRecords jsondic:paramDict finishBlock:^(ClassData* data) {
        if ([data.number isEqualToNumber:@0]) {
            NSDictionary *dic = [NSDictionary dictionaryWithDictionary:data.data];
            
            for (NSArray* array in dic[@"DATA"]) {
                IntegralModel *integralModel = [IntegralModel mj_objectWithKeyValues:array];
                [weakSelf.dataSource addObject:integralModel];
            }
            [weakSelf.integralTableView reloadData];
            weakSelf.totalIntegralLabel.text = [NSString stringWithFormat:@"%@", dic[@"TOTAL_SCORE"]];
        } else {
            NSLog(@"请求失败");
        }
    }];
    
    // 3. 结束刷新(相当于动画)
    [weakSelf.integralTableView endUpdates];
    [weakSelf.integralTableView.infiniteScrollingView stopAnimating];
}

- (void)backLogin {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - lazy load
- (NSMutableArray *)dataSource {
    if (_dataSource == nil) {
        _dataSource = [[NSMutableArray alloc] init];
    }
    return _dataSource;
}

@end
